<?php

/**
 * APIServer
 * 
 * @author ShuangYa
 * @package EUser
 * @category Library
 * @link http://www.sylingd.com/
 */

namespace euser\libs;
use \Sy;

class APIServer {
	public static function callback($serv, $fd, $from_id, $data) {
		$data = Packet::packDecode($data);
		if ($data['data'] === NULL) {
			return;
		}
		if ($data['msg'] !== 'OK') {
			$result = ['error' => 'invalid_param'];
		} else {
			//检查签名
			$app = Sy::service('app')->getClient($data['data']['data']['client_id']);
			$signStr = Sy::service('app')->createSign(json_encode($data['data']['data']), $app['secret']);
			if ($data['data']['sign'] !== $signStr) {
				$result = ['error' => 'invalid_sign'];
			} else {
				//分发
				$router = $data['data']['router'];
				//解析controller名称和action名称
				$last = strrpos($router, '/');
				$controllerName = substr($router, 0, $last);
				$actionName = substr($router, $last + 1);
				//获取操作类
				$controller = Sy::controller($controllerName);
				if (NULL === $controller || !method_exists($controller, 'action' . ucfirst($actionName))) {
					$result = ['error' => 'not_found'];
				} else {
					try {
						$result = call_user_func([$controller, 'action' . ucfirst($actionName)], NULL ,$data['data']['data']);
					} catch (\Exception $e) {
						$result = ['error' => 'internal_server_error'];
					}
				}
			}
		}
		$serv->send($fd, Packet::packEncode($result, 'tcp'), $from_id);
	}
	public static function connect($serv, $fd, $from_id) {
		// $time = time();
		// file_put_contents('/tmp/eu_log.log', "Connected: $time - $fd, $from_id\n", FILE_APPEND);
	}
	public static function close($serv, $fd, $from_id) {
		// $time = time();
		// file_put_contents('/tmp/eu_log.log', "Closed: $time - $fd, $from_id\n", FILE_APPEND);
	}
}